<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="pageData.queryData" layout="inline">
          <a-form-item label="日期">
            <a-range-picker popup-container="html"
                            :style="{ width: '300px' }"
                            class="bacClass"
                            v-model="pageData.queryData.createTimeArr"
            />
          </a-form-item>
          <a-form-item label="流转卡号">
            <a-input
                @press-enter="selectHandler"
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.queryData.flowCardCode"
                allow-clear
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
              v-if="headerShow"
              @click="headerShow = false"
              :strokeWidth="2"
              :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="['查询', '导出']" @export="exports" @select="selectHandler"></Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: calc(100% - 45px)"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="pageData.tc"
          :localeText="localeText1"
          :suppressRowClickSelection="true"
      ></AgGridVuesCopys>
      <paginationCopys
          :page-size="pagination.pageSize"
          :current="pagination.page"
          :total="pagination.total"
          show-total
          show-jumper
          show-page-size
          @change="nextDoRefreshPage"
          @page-size-change="nextDoRefreshSize"
          style="justify-content: center"
      />
    </template>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post, get} from '@/api/http'
import {useTable, usePagination, useTableColumn} from '@/hooks/table'

import {ref, reactive, onMounted} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import {localeText} from '@/api/aggridZw'

import {Message, Modal} from '@arco-design/web-vue'

interface paramData {
  id: any
  examineItem: string | undefined
  minRange: string | undefined
  maxRange: string | undefined
  choosableValue: string | undefined
  defectScore: string | undefined
  chooseScore: string | undefined
  remark: string | undefined
}

export default {
  //查布疵点汇总
  name: 'ChaBuSummaryData',
  setup() {
    //隐藏显示头部
    const headerShow = ref<boolean>(true)
    const pageData = reactive<{
      pageLoading: boolean
      labelColFlex: string
      tc: any
      queryData: any
    }>({
      pageLoading: false,
      labelColFlex: '120px',
      tc: [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
        {
          headerName: '流转卡号',
          field: 'circulatCard',
          pinned: '',
        },
        {
          headerName: '总扣分数',
          field: 'totalBranchNum',
          pinned: '',
        },
      ],
      queryData: {
        createTimeArr: [],
        flowCardCode: '',
      },
    })
    //查询列表
    onMounted(() => {
      selectHandler()
    })

    //切换分页
    const nextDoRefreshPage = (val: any) => {
      pagination.page = val
      doRefresh()
    }
    const nextDoRefreshSize = (val: any) => {
      pagination.pageSize = val
      doRefresh()
    }
    const pagination = usePagination(doRefresh)
    const table = useTable()

    function doRefresh() {
      pageData.pageLoading = true
      if (pageData.queryData.createTimeArr == undefined) {
        pageData.queryData.createTimeArr = []
      }
      post({
        url: 'dwQms/Verifyyarn/findVerifyYarn',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          circulatCard: pageData.queryData.flowCardCode,
          startDate: pageData.queryData.createTimeArr[0],
          endDate: pageData.queryData.createTimeArr[1],
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              let defectNameList: any[] = data.defectName
              let list: any[] = data.list.map((o: any) => {
                let obj = {
                  circulatCard: o.circulatCard,
                  totalBranchNum: o.totalBranchNum,
                }
                for (let index = 0; index < defectNameList.length; index++) {
                  const element = defectNameList[index]
                  let defectNum: any = ''
                  for (let index1 = 0; index1 < o.verifyyarnDetail.length; index1++) {
                    if (element == o.verifyyarnDetail[index1].defectName) {
                      defectNum = o.verifyyarnDetail[index1].defectNum
                      break
                    }
                  }
                  obj['defectName_' + index] = defectNum
                }
                return obj
              })
              let tbList: any[] = [
                {
                  headerName: '流转卡号',
                  field: 'circulatCard',
                  pinned: '',
                },
              ]
              for (let index = 0; index < defectNameList.length; index++) {
                const element = defectNameList[index]
                let obj: any = {}
                obj = {
                  headerName: element,
                  field: 'defectName_' + index,
                  pinned: '',
                }
                tbList.push(obj)
              }
              tbList.push({
                headerName: '总扣分数',
                field: 'totalBranchNum',
                pinned: '',
              })
              useTableColumn(tbList)
              let a = [
                {
                  showRowGroup: 'hide_def',
                  headerName: '',
                  checkboxSelection: true,
                  headerCheckboxSelection: true,
                  pinned: 'left',
                  width: 50,
                  resizable: false,
                  filter: false,
                  sortable: false,
                  minWidth: 50,
                  maxWidth: 50,
                  lockPosition: 'left',
                },
              ]
              pageData.tc = a.concat(tbList)
              table.handleSuccess(list)
              pagination.setTotalSize(data.total)
              gridOption.value.setRowData(list)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }

    const queryData = reactive({
      createTimeArr: [],
      flowCardCode: '',
    })

    // 表格准备事件

    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }

    const localeText1: any = ref(localeText)

    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        //拼接表头
        let head = ''
        let nowRow: any = gridOption.value.getSelectedRows()
        pageData.tc.forEach(function (o: any) {
          if (o['field']) {
            head += '<th>' + o['headerName'] + '</th>'
          }
        })
        let body = ''
        nowRow.forEach(function (o: any) {
          body += '<tr>'
          pageData.tc.forEach(function (o1: any) {
            let key = o1['field']
            if (key) {
              var value = o[key]
              if (value != undefined) {
                body += '<td>' + o[key] + '</td>'
              } else {
                body += '<td></td>'
              }
            }
          })
          body += '</tr>'
        })
        tableToXlsx(head, '查布疵点汇总', body)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    return {
      pagination,
      table,
      pageData,
      selectHandler,
      headerShow,
      queryData,
      nextDoRefreshPage,
      nextDoRefreshSize,
      defaultColDef,
      localeText1,
      gridReady,
      gridOption,
      exports,
    }
  },
  components: {Toolbar, },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
